package com.broada.apm.utils;

import java.util.HashMap;
import java.util.Map;

import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.AtomicLongMap;

public class StatsUtil {

	private static final AtomicLongMap<String> counters = AtomicLongMap.create();
	private static final Map<String, Stopwatch> stopWatchs = Maps.newHashMap();

	public static Map<String, Object> stats() {
		HashMap<String, Object> newHashMap = Maps.newHashMap();
		newHashMap.put("counters", counters.asMap());
		newHashMap.put("watchs", stopWatchs);
		return newHashMap;
	}

	public static void startStopWatch(String name) {
		Stopwatch watch = stopWatchs.get(name);
		if (watch == null) {
			watch = Stopwatch.createUnstarted();
			stopWatchs.put(name, watch);
		}
		if (!watch.isRunning())
			watch.start();
	}

	public static void stopStopWatch(String name) {
		Stopwatch watch = stopWatchs.get(name);
		if (watch == null) {
			watch = Stopwatch.createUnstarted();
			stopWatchs.put(name, watch);
			watch.start();
		}
		if (watch.isRunning())
			watch.stop();
	}

	public static void incrementCounter(String name) {
		counters.incrementAndGet(name);
	}

	public static void addCounter(String name, long delta) {
		counters.addAndGet(name, delta);
	}
}
